#!/bin/bash
# Identify links to a file
# Usage: lnks.sh file [directory]

if [ $# -eq 0 -o $# -gt 2 ] 
then
	echo "Usage: links.sh file [directory]" 1>&2
	exit 1
fi

if [ -d "$1" ]
then
	echo "First argument cannot be a directory." 1>&2
	echo "Usage: links file directory]" 1>&2
	exit 1
else
	file="$1"
fi

if [ $# -eq 1 ]
then
	directory="."
elif [ -d "$2" ]
then
	directory="$2"
else
	echo "Optional second argument must be a directory." 1>&2
	echo "Usage: links file [directory]" 1>&2
	exit 1
fi

# Check that file exists and is a ordinary file:
if [ ! -f "$file" ]
then
	echo "links.sh: $file not found or special file" 1>&2
	exit 1
fi

# Check link count on file
set -- $(ls -l "$file")

linkcnt=$2
if [ "$linkcnt" -eq 1 ] 
then
	echo "links.sh: no other hard links to $file" 1>&2
	exit 0
fi

# Get the inode of the given file
set $(ls -i "$file")

inode=$1

# Find and print the files with that inode number
echo "links: using find to search for links..." 1>&2
find "$directory" -xdev -inum $inode -print

